# Create your views here.

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from django.template import RequestContext
from market.marketData import MarketData
from market.playerData import PlayerData
from market.findNewRepRule2Ter import FindNewRepRule2TerHelper
from market.models import Asset
from market.models import Player
from market.mathView import view2vec
from market.mathView import indexOfAssetInList

###########################################################################################
# this controller is the one calling the view
def viewMarket(request):

	# authentification
	if not request.user.is_authenticated():
		return HttpResponseRedirect('/login/?next=%s' % request.path)

	# the user is here authentified - we get the matching player
	p = PlayerData(request.user.username)
	if( not p.isListedPlayer ):
                msg = '%s is not a listed player' %(request.user.username)
                return HttpResponse( msg )
        
	# we create the market object
	m = MarketData()

	# we call the view with all the data needed
	# market data
	# player object
	# a list of tupple (Asset, proba) to avoid complicated request in the view
	return render_to_response(
                'market/viewMarket.html',
                {'market':m, 'player':p, 'playerProbabilities':p.getViewMainFund().getFullView()},
                context_instance=RequestContext(request) )


###########################################################################################
# implementation of rules 2 : the player change his strategy submitting a new one
# this is "part 2" where the new strategy is apply and the page with the new state returned
# "part 1" is implemented in the next function
def applyNewRepartition( player, repartition, request ):
        player.setNewView( repartition )
        if( player.setRepartitionString != "" ):
                return HttpResponse( 'errorString:  %s'  %player.setRepartitionString )
        return HttpResponseRedirect("/celibax/")


###########################################################################################
# helper for submit repartition
def getPercentageAssociatedToName(request, assetName, status):
        tmp = request.POST[assetName]
        if tmp == "":
                return 0
        try:
                return float(tmp)
        except Exception:
                status.append(' pb with percentage associated to %s' %assetName )
                return 0
###########################################################################################
# implementation of rules 2 : the player change his strategy submitting a new one
# this is "part 1" where the new strategy is extract from the post request 
def SubmitNewRepartition(request):

        # authentification
	if not request.user.is_authenticated():
		return HttpResponseRedirect('/login/?next=%s' % request.path)
	
        if request.method == 'GET':
                return HttpResponseRedirect("/celibax/")
        elif request.method == 'POST':
                # the user is here authentified - we get the matching player
                p = PlayerData(request.user.username)
                # string are un mutable so we cannot pass a strin for the status
                status = []
                repartition = [ getPercentageAssociatedToName(request,a.name, status) for a in Asset.objects.all()]
                if( len(status) == 0 ):
                        return applyNewRepartition( p, repartition, request )
                else:
                        return HttpResponse( str(status) )


###########################################################################################
# implementation of rules 2Ter : the player change his strategy via selling a specified number of the specified asset
def sellAsset(request):

        # authentification
	if not request.user.is_authenticated():
		return HttpResponseRedirect('/login/?next=%s' % request.path)
	
        if request.method == 'GET':
                return HttpResponseRedirect("/celibax/")
        elif request.method == 'POST':
                # the user is here authentified - we get the matching player
                p = PlayerData(request.user.username)
                
                numberOfSoldAsset0 = request.POST["numberSold"]
                numberOfSoldAsset = 0
                try:
                        numberOfSoldAsset = float(numberOfSoldAsset0)
                except Exception:
                        numberOfSoldAsset = -1
                if numberOfSoldAsset == -1:
                        return HttpResponse( "please check the number of asset you want to sell" )
           
                m = MarketData()
                totalNumberOfAssetBefore = p.getMainFundTotalNumberOfAssets()
                indexOfSoldAsset = indexOfAssetInList( request.POST["soldAsset"], m.assets)
                indexOdBoughtAsset = indexOfAssetInList( request.POST["boughtAsset"], m.assets)
                nPlayers =  len(Player.objects.all())
                marketPrices = view2vec( m.getMarketView(), m.assets)
                rb = view2vec( p.getViewMainFund(), m.assets)
                newRepHelper = FindNewRepRule2TerHelper( totalNumberOfAssetBefore, rb, indexOfSoldAsset, numberOfSoldAsset, indexOdBoughtAsset, marketPrices, nPlayers )
                if( newRepHelper.initializationStatusString != "" ):
                        return HttpResponse( newRepHelper.initializationStatusString )
                tmp = newRepHelper.findNewRepRule2Ter()
                if( tmp[1] == -999 ):
                        return HttpResponse( 'error in newton solve %s' %tmp[1] )
                return applyNewRepartition( p, tmp[0], request )


###########################################################################################
# return the page with the rules and the explanation
def celibaxRules(request):
        return render_to_response(
                        'market/rules.html',
                        {},
                        context_instance=RequestContext(request) )

###########################################################################################
# return the page with the rules and the explanation
def logoutView(request):
        logout(request)
        return HttpResponseRedirect("/celibax/")


###########################################################################################
# helper for submit repartition of mtm for strategy. the main strategy must have 50% at least of the mtm repartition
def getPercentageAssociatedToStrategy(request, stratName, mainStratName, status):
        tmp = request.POST[assetName]
        res = -1
        if tmp == "":
                return 0
        try:
                return float(tmp)
        except Exception:
                status.append(' pb with percentage associated to %s' %assetName )
                return res

        
###########################################################################################
# return the page with the rules and the explanation
def SubmitNewStrategyMtMRep(request):
        # authentification
	if not request.user.is_authenticated():
		return HttpResponseRedirect('/login/?next=%s' % request.path)
        if request.method == 'GET':
                return HttpResponseRedirect("/celibax/")
        # execute the request
        elif request.method == 'POST':
                # the user is here authentified - we get the matching player
                p = PlayerData(request.user.username)
                # string are un mutable so we cannot pass a strin for the status
                status = []
                repartition = [ [s.name,getPercentageAssociatedToName(request,s.name, status)] for s in Strategy.objects.all()]
                if( len(status) == 0 ):
                        p.setNewStratMtMRep( repartition, request )
                        if( p.setRepartitionString != "" ):
                                return HttpResponse( 'errorString:  %s'  %p.setRepartitionString )
                        return HttpResponseRedirect("/celibax/")
                else:
                        return HttpResponse( str(status) )

